package com.bisp30;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.bisp30.bookinfo.BookInfomation;
import com.bisp30.bookinfo.BookListXMLParser;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BookList extends ListActivity {
	
	 private List<BookInfomation> mData;
	 private URL url;
	 private HttpURLConnection conn=null;
	 private InputStream inStream;
     
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        
	        
	        mData = getData();
	        MyAdapter adapter = new MyAdapter(this);
	        setListAdapter(adapter);
	    }
	 
	    private List<BookInfomation> getData() {
	        List<BookInfomation> list = new ArrayList<BookInfomation>();
	        
	        try {
				url = new URL("http://172.19.100.140:8080/MedoBook/BookList.xml");				
				conn = (HttpURLConnection)url.openConnection();
				conn.setDoInput(true);
				conn.setRequestProperty("Content-Type", "text/xml");
				//conn.setRequestProperty("Connection", "Keep-Alive");		
				conn.setRequestMethod("GET");	
				conn.connect();
				System.out.println("Allven --------"+conn.getResponseCode());			
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {  
					inStream = conn.getInputStream();//打开连接的输入流
				}
				else{
					Toast.makeText(this, "连接网络失败，请检查网络 ！", Toast.LENGTH_LONG).show();
				}
	        }catch (Exception e) {
	        		Toast.makeText(this, "网络异常，请检查网络 ！", Toast.LENGTH_LONG).show();		
			}
	        
	    	try {
				if(inStream != null){
					list = BookListXMLParser.readXml(inStream);
				}
				else{
					Toast.makeText(this, "XML解析失败", Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
				//Log.e(TAG, e.toString());
				Toast.makeText(this, "XML解析失败", Toast.LENGTH_LONG).show();
			} 
	 
			return list;
	    }
	     
	    @Override
		protected void onListItemClick(ListView l, View v, int position, long id) {
			// TODO Auto-generated method stub
			super.onListItemClick(l, v, position, id);
			
			Intent intent = new Intent();
			intent.setClass(BookList.this, BookReader.class);
			startActivity(intent);
			
		}
	    // listview中点击按键弹出对话框
		public void showInfo(){
	        new AlertDialog.Builder(this)
	        .setTitle("我的listview")
	        .setMessage("介绍...")
	        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	            	
	            }
	        })
	        .show();
	         
	    }
	     

		public final class ViewHolder{
	        public ImageView icon;
	        public TextView name;
	        public TextView resume;
	        //public Button viewBtn;
	    }
	     
	    public class MyAdapter extends BaseAdapter{
	 
	        private LayoutInflater mInflater;
	         
	        public MyAdapter(Context context){
	            this.mInflater = LayoutInflater.from(context);
	        }
	        @Override
	        public int getCount() {
	            // TODO Auto-generated method stub
	            return mData.size();
	        }
	 
	        @Override
	        public Object getItem(int arg0) {
	            // TODO Auto-generated method stub
	            return null;
	        }
	 
	        @Override
	        public long getItemId(int arg0) {
	            // TODO Auto-generated method stub
	            return 0;
	        }
	        
	        /**
	         * 获取网落图片资源 
	         * @param url
	         * @return
	         */
	        public  Bitmap getHttpBitmap(String url){
	        	URL myFileURL;
	        	Bitmap bitmap=null;
	        	try{
	        		myFileURL = new URL(url);
	        		HttpURLConnection iconConn=(HttpURLConnection)myFileURL.openConnection();
	        		//设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
	        		iconConn.setConnectTimeout(6000);
	        		//连接设置获得数据流
	        		iconConn.setDoInput(true);
	        		//不使用缓存
	        		iconConn.setUseCaches(false);
	        		//这句可有可无，没有影响
	        		//conn.connect();
	        		//得到数据流
	        		InputStream is = iconConn.getInputStream();
	        		//解析得到图片
	        		bitmap = BitmapFactory.decodeStream(is);
	        		//关闭数据流
	        		is.close();
	        	}catch(Exception e){
	        		e.printStackTrace();
	        	}
	        	
	    		return bitmap;
	        	
	        }
	        
	        public View getView(int position, View convertView, ViewGroup parent) {
	             
	            ViewHolder holder = null;
	            if (convertView == null) {
	                 
	                holder=new ViewHolder();  	                 
	                convertView = mInflater.inflate(R.layout.booklist, null);
	                holder.icon = (ImageView)convertView.findViewById(R.id.img);
	                holder.name = (TextView)convertView.findViewById(R.id.title);
	                holder.resume = (TextView)convertView.findViewById(R.id.info);
	                //holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
	                convertView.setTag(holder);
	                 
	            }else {
	                 
	                holder = (ViewHolder)convertView.getTag();
	            }
	            //Uri iconUri = new Uri(mData.get(position).getIcon());
	            String url = (String)mData.get(position).getIcon();
	            Bitmap bitmap = getHttpBitmap(url);
	            if(bitmap == null){
	            	//System.out.println("Allven  bitmap--------"+mData.get(position).getIcon());
	            	holder.icon.setImageResource(R.drawable.icon);
	            }
	            else{
	            	//System.out.println("Allven bitmap--11111111------null");
	            	holder.icon.setImageBitmap(bitmap);	
	            }
	                        
	            holder.name.setText((String)mData.get(position).getName());
	            holder.resume.setText((String)mData.get(position).getResume());	             
				return convertView;
	        }
	         
	    }

}
